{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tce3stUlHN0L"
      },
      "source": [
        "##### Copyright 2020 The TensorFlow IO Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qFdPvlXBOdUN"
      },
      "source": [
        "# 音频数据准备和增强"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MfBg1C5NB3X0"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td><a target=\"_blank\" href=\"https://tensorflow.google.cn/io/tutorials/audio\"><img src=\"https://tensorflow.google.cn/images/tf_logo_32px.png\">在 TensorFlow.org 上查看</a></td>\n",
        "  <td><a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/zh-cn/io/tutorials/audio.ipynb\"><img src=\"https://tensorflow.google.cn/images/colab_logo_32px.png\">在 Google Colab 中运行</a></td>\n",
        "  <td><a target=\"_blank\" href=\"https://github.com/tensorflow/docs-l10n/blob/master/site/zh-cn/io/tutorials/audio.ipynb\"><img src=\"https://tensorflow.google.cn/images/GitHub-Mark-32px.png\">在 GitHub 上查看源代码</a></td>\n",
        "      <td><a href=\"https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/zh-cn/io/tutorials/audio.ipynb\"><img src=\"https://tensorflow.google.cn/images/download_logo_32px.png\">下载笔记本</a></td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xHxb-dlhMIzW"
      },
      "source": [
        "## 概述\n",
        "\n",
        "自动语音识别面临的最大挑战之一是音频数据的准备和增强。音频数据分析可能涉及时域或频域，与图像等其他数据源相比，这提高了复杂性。\n",
        "\n",
        "作为 TensorFlow 生态系统的一部分，`tensorflow-io` 软件包提供了不少与音频相关的 API。这些 API 非常有用，可简化音频数据的准备和增强。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MUXex9ctTuDB"
      },
      "source": [
        "## 设置"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "upgCc3gXybsA"
      },
      "source": [
        "### 安装要求的软件包，然后重新启动运行时"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "uUDYyMZRfkX4"
      },
      "outputs": [],
      "source": [
        "!pip install tensorflow-io"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "J0ZKhA6s0Pjp"
      },
      "source": [
        "## 使用方法"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yZmI7l_GykcW"
      },
      "source": [
        "### 读取音频文件\n",
        "\n",
        "在 TensorFlow IO 中，利用类 `tfio.audio.AudioIOTensor` 可以将音频文件读取到延迟加载的 `IOTensor` 中："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "nS3eTBvjt-O5"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "import tensorflow_io as tfio\n",
        "\n",
        "audio = tfio.audio.AudioIOTensor('gs://cloud-samples-tests/speech/brooklyn.flac')\n",
        "\n",
        "print(audio)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "z9GCyPWNuOm7"
      },
      "source": [
        "在上面的示例中，Flac 文件 `brooklyn.flac` 来自 [Google Cloud](https://cloud.google.com/speech-to-text/docs/quickstart-gcloud) 中可公开访问的音频片段。\n",
        "\n",
        "示例中直接使用 GCS 地址 `gs://cloud-samples-tests/speech/brooklyn.flac`，因为 TensorFlow 支持 GCS 文件系统。除了 `Flac` 格式，凭借自动文件格式检测，`AudioIOTensor` 还支持 `WAV`、`Ogg`、`MP3` 和 `MP4A` 格式。\n",
        "\n",
        "`AudioIOTensor` 是一个延迟加载张量，因此，刚开始只显示形状、dtype 和采样率。`AudioIOTensor` 的形状用 `[samples, channels]` 表示，这表示您加载的音频片段是单声道音频（`int16` 类型的 `28979` 个样本）。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IF_kYz_o2DH4"
      },
      "source": [
        "仅需要时才会读取该音频片段的内容。要读取音频片段的内容，可通过 `to_tensor()` 将 `AudioIOTensor` 转换为 `Tensor`，也可以通过切片读取。如果只需要一个大音频片段的一小部分，切片尤其实用："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wtM_ixN724xb"
      },
      "outputs": [],
      "source": [
        "audio_slice = audio[100:]\n",
        "\n",
        "# remove last dimension\n",
        "audio_tensor = tf.squeeze(audio_slice, axis=[-1])\n",
        "\n",
        "print(audio_tensor)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IGnbXuVnSo8T"
      },
      "source": [
        "音频可通过以下方式播放："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0rLbVxuFSvVO"
      },
      "outputs": [],
      "source": [
        "from IPython.display import Audio\n",
        "\n",
        "Audio(audio_tensor.numpy(), rate=audio.rate.numpy())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fmt4cn304IbG"
      },
      "source": [
        "更方便的方式是，将张量转换为浮点数并在计算图中显示音频片段："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZpwajOeR4UMU"
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n",
        "\n",
        "\n",
        "tensor = tf.cast(audio_tensor, tf.float32) / 32768.0\n",
        "\n",
        "plt.figure()\n",
        "plt.plot(tensor.numpy())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "86qE8BPl5rcA"
      },
      "source": [
        "### 降噪\n",
        "\n",
        "为音频降噪有时很有意义，这可以通过 API `tfio.audio.trim` 实现。从该 API 返回的是片段的一对 `[start, stop]` 位置："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "eEa0Z5U26Ep3"
      },
      "outputs": [],
      "source": [
        "position = tfio.audio.trim(tensor, axis=0, epsilon=0.1)\n",
        "print(position)\n",
        "\n",
        "start = position[0]\n",
        "stop = position[1]\n",
        "print(start, stop)\n",
        "\n",
        "processed = tensor[start:stop]\n",
        "\n",
        "plt.figure()\n",
        "plt.plot(processed.numpy())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ineBzDeu-lTh"
      },
      "source": [
        "### 淡入和淡出\n",
        "\n",
        "一种有用的音频工程技术是淡入淡出，也就是逐渐增强或减弱音频信号。这可以通过 `tfio.audio.fade` 实现。`tfio.audio.fade` 支持不同的淡入淡出形状，如 `linear`、`logarithmic` 或 `exponential`："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LfZo0XaaAaeM"
      },
      "outputs": [],
      "source": [
        "fade = tfio.audio.fade(\n",
        "    processed, fade_in=1000, fade_out=2000, mode=\"logarithmic\")\n",
        "\n",
        "plt.figure()\n",
        "plt.plot(fade.numpy())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7rhLvOSZB0k0"
      },
      "source": [
        "### 声谱图\n",
        "\n",
        "高级音频处理通常需要根据时间调整音频频率。在 `tensorflow-io` 中，可通过 `tfio.audio.spectrogram` 将波形图转换为声谱图。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UyFMBK-LDDnN"
      },
      "outputs": [],
      "source": [
        "# Convert to spectrogram\n",
        "spectrogram = tfio.audio.spectrogram(\n",
        "    fade, nfft=512, window=512, stride=256)\n",
        "\n",
        "plt.figure()\n",
        "plt.imshow(tf.math.log(spectrogram).numpy())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pZ92HnbJGHBS"
      },
      "source": [
        "也可以转换为其他不同的比例："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZgyedQdxGM2y"
      },
      "outputs": [],
      "source": [
        "# Convert to mel-spectrogram\n",
        "mel_spectrogram = tfio.audio.melscale(\n",
        "    spectrogram, rate=16000, mels=128, fmin=0, fmax=8000)\n",
        "\n",
        "\n",
        "plt.figure()\n",
        "plt.imshow(tf.math.log(mel_spectrogram).numpy())\n",
        "\n",
        "# Convert to db scale mel-spectrogram\n",
        "dbscale_mel_spectrogram = tfio.audio.dbscale(\n",
        "    mel_spectrogram, top_db=80)\n",
        "\n",
        "plt.figure()\n",
        "plt.imshow(dbscale_mel_spectrogram.numpy())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nXd776xNIr_I"
      },
      "source": [
        "### SpecAugment\n",
        "\n",
        "除上述数据准备和增强 API 外，`tensorflow-io` 软件包还提供了高级声谱图增强，最主要的是在 [SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition (Park et al., 2019)](https://arxiv.org/pdf/1904.08779.pdf) 中讨论的频率掩蔽和时间掩蔽。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dajm7k-2J5l7"
      },
      "source": [
        "#### 频率掩蔽\n",
        "\n",
        "在频率掩蔽中，对频率通道 `[f0, f0 + f)` 进行掩蔽，其中 `f` 选自从 `0` 到频率掩蔽参数 `F` 的均匀分布，而 `f0` 则选自 `(0, ν − f)`，其中 `ν` 是频率通道的数量。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "kLEdfkkoK27A"
      },
      "outputs": [],
      "source": [
        "# Freq masking\n",
        "freq_mask = tfio.audio.freq_mask(dbscale_mel_spectrogram, param=10)\n",
        "\n",
        "plt.figure()\n",
        "plt.imshow(freq_mask.numpy())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_luycpCWLe5l"
      },
      "source": [
        "#### 时间掩蔽\n",
        "\n",
        "在时间掩蔽中，对 `t` 个连续时间步骤 `[t0, t0 + t)` 进行掩蔽，其中 `t` 选自从 `0` 到时间掩蔽参数 `T` 的均匀分布，而 `t0` 则选自 `[0, τ − t)`，其中 `τ` 是时间步数。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "G1ie8J3wMMEI"
      },
      "outputs": [],
      "source": [
        "# Time masking\n",
        "time_mask = tfio.audio.time_mask(dbscale_mel_spectrogram, param=10)\n",
        "\n",
        "plt.figure()\n",
        "plt.imshow(time_mask.numpy())"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [
        "Tce3stUlHN0L"
      ],
      "name": "audio.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
